import { docCookies } from "@/utils/docCookie";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import ErrorPage from "../views/Error.vue";
import message from "ant-design-vue/es/message";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/edgex",
    name: "Edgex",
    component: () => import("../views/Edgex.vue"),
    meta: {
      belong: "Edgex",
    },
  },
  {
    path: "/edgex/:prefix",
    name: "EdgexDetail",
    component: () => import("../views/EdgexDetail.vue"),
    meta: {
      belong: "Edgex",
    },
  },
  {
    path: "/device",
    name: "Device",
    component: () => import("../views/Device.vue"),
    meta: {
      menu: "Cloud",
      belong: "Device",
    },
  },
  {
    path: "/device/detail/:id",
    name: "DeviceDetail",
    component: () => import("@/views/DeviceDetail.vue"),
    meta: {
      menu: "Cloud",
      belong: "Device",
    },
  },
  {
    path: "/devicedata",
    name: "DeviceData",
    component: () => import("@/views/DeviceData.vue"),
    meta: {
      menu: "Cloud",
      belong: "DeviceData",
    },
  },
  {
    path: "/display/chart",
    name: "DisplayChart",
    component: () => import("@/views/DisplayChart.vue"),
    meta: {
      menu: "Display",
      belong: "DisplayChart",
    },
  },
  {
    path: "/display/park",
    name: "DisplayPark",
    component: () => import("../views/DisplayPark.vue"),
    meta: {
      menu: "Display",
      belong: "DisplayPark",
    },
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("../views/Register.vue"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  { path: "/:pathMatch(.*)*", name: "not-found", component: ErrorPage },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const session_token = docCookies.getItem("session_token");
  if (session_token) {
    // 已登录
    if (to.name === "Login") {
      next({
        name: "Edgex",
      });
    } else {
      next();
    }
  } else {
    // 未登录
    if (to.name === "Login" || to.name === "Register") next();
    else {
      message.warn("未登录");
      next({
        name: "Login",
      });
    }
  }
});

export default router;
